import argparse
import numpy as np
import ast  # 用来安全地把字符串转成列表、元组等Python对象

parser = argparse.ArgumentParser("Grid World Environment")

# 支持传入多个数，比如 --env-size 5 5
parser.add_argument("--env-size", nargs=2, type=int, default=[5, 5], help="Grid size: rows cols")

parser.add_argument("--start-state", nargs=2, type=int, default=[2, 2], help="Start position: x y")

parser.add_argument("--target-state", nargs=2, type=int, default=[4, 4], help="Target position: x y")

# forbidden-states 传字符串，然后用 ast.literal_eval 转换成列表
parser.add_argument("--forbidden-states", type=str, default="[(2,1),(3,3),(1,3)]",
                    help="Forbidden states list, e.g. '[(2,1),(3,3),(1,3)]'")

parser.add_argument("--reward-target", type=float, default=2)

parser.add_argument("--reward-forbidden", type=float, default=-1)

parser.add_argument("--reward-step", type=float, default=0)

parser.add_argument("--action-space", type=str,
                    default="[(0, -1), (0, 1), (-1, 0), (1, 0), (0, 0)]",
                    help="Action space list, e.g. '[(0,1),(1,0),(0,-1),(-1,0),(0,0)]'")

parser.add_argument("--debug", type=bool, default=False)

parser.add_argument("--animation-interval", type=float, default=0.2)

args = parser.parse_args()

# 解析字符串转为Python对象
args.forbidden_states = ast.literal_eval(args.forbidden_states)
args.action_space = ast.literal_eval(args.action_space)

# 把list转成tuple，防止代码里使用元组出错
args.env_size = tuple(args.env_size)
args.start_state = tuple(args.start_state)
args.target_state = tuple(args.target_state)

def validate_environment_parameters(env_size, start_state, target_state, forbidden_states):
    if not (isinstance(env_size, tuple) and len(env_size) == 2):
        raise ValueError("Invalid environment size. Expected a tuple (rows, cols) with positive dimensions.")
    
    for i in range(2):
        assert start_state[i] < env_size[i], "start_state out of env range"
        assert target_state[i] < env_size[i], "target_state out of env range"
        for j in range(len(forbidden_states)):
            assert forbidden_states[j][i] < env_size[i], "forbidden_states out of env range"

try:
    validate_environment_parameters(args.env_size, args.start_state, args.target_state, args.forbidden_states)
except Exception as e:
    print("Error:", e)
    exit(1)

# 这里你就可以正常使用 args.xxx 了
print("env_size:", args.env_size)
print("start_state:", args.start_state)
print("target_state:", args.target_state)
print("forbidden_states:", args.forbidden_states)
print("action_space:", args.action_space)
